import api from '@/api'
import { isCode, showMessage, matchMonth } from '@/utils'
import { clearCookie } from "@/utils/cookie.js";
import router from '@/router'
const initState = () => {
    return {
        equipment: "",
        leftMenu: "",
        currentWidth: "",
        userInfo: "",
    };
};

const state = initState();

const mutations = {

    //更新用户信息
    setUserInfo(state, payload) {
        state.userInfo = payload;
        if (!state.userInfo.icon) {
            state.userInfo.icon = require('@/assets/images/profile/pc/avatar.png');
        }
    },

    //获取当前宽度
    getCurrentWidth(state, payload) {
        state.currentWidth = payload
    },

    //获取当前设备
    getCurrentEquipment(state, payload) {
        state.equipment = payload
    },

    //左侧菜单展开
    getLeftMenu(state, payload) {
        state.leftMenu = payload
    },

    resetState(state) {
        Object.assign(state, initState());
    },

    //用户登出
    userSignout() {
        clearCookie("token")
        Object.keys(this.state).map((item, index) => {
            this.commit(item + '/resetState');
        })
        router.push('/')
    },
};

const actions = {
    //获取用户信息
    async getUserInfo() {
        let res = await api.profile.getUserInfoApi({
            userId: this.state.common.userInfo.userId,
        })
        if (isCode(res)) {
            let userInfo = {
                isLogin: true,
                email: res.data.user.email,
                birth: res.data.user.birth,
                icon: res.data.user.icon,
                userId: res.data.user.id,
                nickname: res.data.user.nickname,
                createtime: matchMonth(res.data.user.createtime),
                last_login_time: matchMonth(res.data.user.logintime),
                book_highlights: res.data.count.Book_highlights,
                ideas: res.data.count.Ideas,
                total_entries: res.data.count.Total_entries,
                web_clippings: res.data.count.Web_clippings,
            }
            this.commit('common/setUserInfo', userInfo);
        }
    },
    //用户信息修改
    async updateUserInfo() {
        let formData = new FormData();
        formData.append("userId", this.state.common.userInfo.userId);
        formData.append("birth", this.state.common.userInfo.birth);
        formData.append("nickname", this.state.common.userInfo.nickname);
        let res = await api.profile.updateUserInfoApi(formData)
        if (isCode(res)) {
            showMessage(res.message_en, 'success')
            this.dispatch('common/getUserInfo')
        }
    },

};

const getters = {};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
};